<!--
 * @Description: Ping工具
 * @Author: 0001100986/LiuShuai
 * @Date: 2021-08-06 08:56:52
 * @LastEditTime: 2021-11-11 16:30:03
 * @LastEditors: 0001100986/LiuShuai
-->
<template>
  <div class="page-content" style="padding: 0" v-loading="spinShow">
    <el-form :inline="true" ref="form" :model="form" label-width="80px">
      <el-form-item label="源IP" key="source" prop="source">
        <el-select v-model.trim="form.source" clearable filterable @change="changePort">
          <template v-for="(item, index) in protIps">
            <!-- 过滤空IP -->
            <template v-if="item['IP'] !== null">
              <!-- 过滤物理口 -->
              <template v-if="item['name'].indexOf('gei') > -1">
                <el-option
                  :key="index"
                  :value="item['id']"
                  :label="item['IP']"
                >端口{{item.name.substring(item.name.indexOf('/') + 1, item.name.length)}} - {{ item['IP'] }} - {{item.status ? 'DOWN' : 'UP'}}</el-option>
              </template>
              <!-- 过滤隧道口 -->
              <template v-if="item['name'].indexOf('tunnel') > -1">
                <el-option
                  :key="index"
                  :value="item['id']"
                  :label="item['IP']"
                >隧道{{item.name.substring(item.name.indexOf('l') + 1, item.name.length)}} - {{ item['IP'] }} - {{item.operStatus ? 'DOWN' : 'UP'}}</el-option>
              </template>
              <!-- 过滤4G口 -->
              <template v-if="item['name'].indexOf('cellular') > -1">
                <el-option
                  :key="index"
                  :value="item['id']"
                  :label="item['IP']"
                >4G/{{item.name.substring(item.name.indexOf('/') + 1, item.name.length)}} - {{ item['IP'] }} - {{item.operStatus ? 'DOWN' : 'UP'}}</el-option>
              </template>
            </template>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="VRF名称" key="vrf" prop="vrf" v-if=" form.vrf ">
        <el-input
          type="text"
          v-model.trim="form.vrf"
          disabled
          placeholder
          style="padding-right: 15px"
        />
      </el-form-item>
      <el-form-item
        label="目标IP"
        key="dest"
        prop="dest"
        :rules="{required: true,  message: '请输入目标IP',trigger: 'blur'}"
      >
        <el-input type="text" v-model.trim="form.dest" placeholder="请输入IP地址" clearable />
      </el-form-item>
      <el-form-item
        label="间隔数"
        key="interval"
        prop="interval"
        :rules="{
              type: 'number',
              required: true,
              message: '范围：2-10秒',
              trigger: 'change',
            }"
      >
        <el-input-number :max="10" :min="2" v-model.trim="form.interval"></el-input-number>
      </el-form-item>
      <el-form-item
        label="包大小"
        key="size"
        prop="size"
        :rules="{
              type: 'number',
              required: true,
              message: '范围：36-8192',
              trigger: 'change',
            }"
      >
        <el-input-number :max="8192" :min="36" v-model.trim="form.size"></el-input-number>
      </el-form-item>
      <el-form-item
        label="次数"
        key="sum"
        prop="sum"
        :rules="{
              type: 'number',
              required: true,
              message: '范围：1-100次',
              trigger: 'change',
            }"
      >
        <el-input-number :max="100" :min="1" v-model.trim="form.sum"></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button size="default" type="primary" @click="handleSubmit" style="margin-left:80px">确认</el-button>
      </el-form-item>
    </el-form>
    <div class="ping-result">
      <ul>
        <li>
          <label>已发送</label>
          <span>{{ pingres["send-pkts"] }}</span>
        </li>
        <li>
          <label>已接收</label>
          <span>{{ pingres["rcv-pkts"] }}</span>
        </li>
        <li>
          <label>丢失</label>
          <span>{{ pingres["rcv-pkts"] === pingres["send-pkts"] ? "0" : ((pingres["send-pkts"] - pingres["rcv-pkts"]) / pingres["send-pkts"]) * 100 + "%" }}</span>
        </li>
        <li>
          <label>最短</label>
          <span>{{ pingres["min-time"] }}ms</span>
        </li>
        <li>
          <label>最长</label>
          <span>{{ pingres["max-time"] }}ms</span>
        </li>
        <li>
          <label>平均</label>
          <span>{{ pingres["avg-time"] }}ms</span>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
export default {
  props: ['ne'],
  data () {
    return {
      // 端口IP
      protIps: [],
      // 表单参数
      form: {
        source: null,
        dest: '',
        sum: 1,
        interval: 2,
        size: 36,
        vrf: null
      },
      spinShow: false,
      // PING结果
      pingres: {
        // 最大时延
        'max-time': 0,
        // 发送包
        'send-pkts': 0,
        // 最小时延
        'min-time': 0,
        // 接收包
        'rcv-pkts': 0,
        // 平均时延
        'avg-time': 0,
        'serial-num': 5
      }
    };
  },
  // 加载DOM后执行
  mounted () {
    let _this = this;
    _this.$nextTick(() => {
      // 获取网元下的端口IP
      _this.getProtIp();
      // 订阅PING消息
      _this.$ws.registerDgQueueListener('ping.command.message.get', _this.dealStart);
    });
  },
  // 销毁
  beforeDestroy () {
    // 执行销毁
    this.$ws.unregisterDgQueueListener(this.dealStart);
  },
  methods: {
    // 处理结果推送
    dealStart (data) {
      let _this = this;
      if (data && data.payload) {
        _this.pingres = data.payload;
        _this.spinShow = false;
        setTimeout(() => {
          _this.$message.success('执行完成！');
        }, 300);
      }
    },
    // 获取端口IP
    getProtIp () {
      let _this = this;
      let params = {
        commandCode: 'statics.ports',
        paras: {
          isWAN: false,
          status: 0
        }
      };
      _this.$http.post({
        url: '/api/resource/nemng/command/' + _this.ne.id,
        data: params
      }).then((res) => {
        if (res.length > 0) {
          res.map((item, index) => {
            item.id = index + 1;
          });
        }
        _this.protIps = res;
      });
    },
    // 提交PING
    handleSubmit () {
      let _this = this;
      _this.spinShow = true;
      _this.$refs['form'].validate((valid) => {
        if (valid) {
          let params = {
            neId: _this.ne.id,
            sourceIp: _this.form.source,
            dstIp: _this.form.dest,
            repeat: _this.form.sum.toString(),
            interval: _this.form.interval.toString(),
            size: _this.form.size.toString(),
          };
          for (let i = 0; i < _this.protIps.length; i++) {
            if (_this.protIps[i]['IP'] === params.sourceIp) {
              // params.vrf = _this.protIps[i]['vrf'];
              params.vrf = _this.form.vrf;
            }
          }
          _this.$http.post({
            url: '/api/sdwan/ne/ping',
            data: params
          }).then((res) => {
            let { status } = res;
            if (status === '0') {
              _this.$message.info('已发送请求，请耐心等待！');
            } else {
              _this.spinShow = false;
            }
          }).catch(err => {
            _this.spinShow = false;
          });
        } else {
          _this.spinShow = false;
          _this.$message.error('请检查必填项！');
        }
      });
    },
    // 选择端口 过滤Vrf
    changePort (val) {
      let _this = this;
      if (val) {
        for (let i = 0; i < _this.protIps.length; i++) {
          if (_this.protIps[i].id && _this.protIps[i].id === val) {
            _this.form.vrf = _this.protIps[i].vrf;
            _this.form.source = _this.protIps[i].IP;
          }
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;
  .ping-result {
    border: 1px solid #e8eaec;
    border-bottom: 0;
    border-right: 0;
    width: 100%;
    overflow: auto;
    margin-bottom: 10px;
    ul {
      list-style: none;
      li {
        width: calc(33.3333% - 1px);
        height: 100px;
        float: left;
        border-right: 1px solid #e8eaec;
        border-bottom: 1px solid #e8eaec;
        label {
          display: block;
          margin: 0;
          padding: 15px;
        }
        span {
          text-align: center;
          display: block;
          width: 100%;
          font-size: 20px;
          font-weight: 500;
          padding: 0;
          margin: 0 auto;
          color: #1495eb;
        }
      }
      &:last-child::after {
        display: block;
        clear: both;
        content: "";
        overflow: hidden;
      }
    }
  }
  ::v-deep .el-input-number {
    width: 217px;
  }
}
</style>